﻿using IQIGame.Onigao.Framework;

namespace IQIGame.Onigao.Game
{
    /// <summary>
    /// 类名 : 列表的Unit对象的更新
    /// 作者 : Canyon / 龚阳辉
    /// 日期 : 2024-08-30 14:29
    /// 功能 : 
    /// </summary>
    public class ListUnitUpdate<T> where T : UIBaseNode
    {
        private ListUnitMappingData<T> dataMapping;
        private bool isInitUpdate = false;

        public ListUnitUpdate(ListUnitMappingData<T> dataMapping)
        {
            this.dataMapping = dataMapping;
        }

        public void AddUpdate()
        {
            if (this.isInitUpdate)
            {
                return;
            }
            this.isInitUpdate = true;
            FrameworkEntry.MonoDriver.updateEvent += OnUpdate;
        }

        private void RemoveUpdate()
        {
            if (!this.isInitUpdate)
            {
                return;
            }
            this.isInitUpdate = false;
            FrameworkEntry.MonoDriver.updateEvent -= OnUpdate;
        }

        private void OnUpdate(float deltaTime, float unscaledDeltaTime)
        {
            if (!this.isInitUpdate)
            {
                return;
            }
            var activeUnits = this.dataMapping.GetActiveUnits();
            foreach (var unit in activeUnits)
            {
                if (unit.isUpdate)
                {
                    unit.Update(deltaTime, unscaledDeltaTime);
                }
            }
        }

        public void Clear()
        {
            this.dataMapping = null;
            this.RemoveUpdate();
        }
    }
}
